// OtaEventListener.java
package com.cs.deviceManager.mqtt.ota.listener;

import com.cs.deviceManager.device.DeviceEventListener;
import com.cs.deviceManager.mqtt.ota.FirmwareUpdater;
import com.cs.deviceManager.mqtt.ota.manager.OtaActiveManager;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

/**
 * OTA 专用事件监听器（单例）
 * 负责将设备二进制消息转发给当前活跃的 FirmwareUpdater
 */
@Component
public class OtaEventListener implements DeviceEventListener {

    @Resource
    private OtaActiveManager otaActiveManager;

    @Override
    public void onDeviceBinary(String deviceId, byte[] data) {
        FirmwareUpdater updater = otaActiveManager.getActiveUpdater(deviceId);
        if (updater != null) {
            updater.handleReceivedData(data);
        }
        // 否则：无活跃 OTA 任务，忽略
    }

    @Override
    public void onDeviceConnected(String deviceId) {
        // 可选：OTA 过程中设备断线重连
    }

    @Override
    public void onDeviceDisconnected(String deviceId) {
        // 可选：断开时取消 OTA
        FirmwareUpdater updater = otaActiveManager.getActiveUpdater(deviceId);
        if (updater != null) {
            updater.handleError("设备断开连接");
        }
    }

    @Override
    public void onDeviceTelemetry(String deviceId, String data) {
        // 其他消息不处理
    }

    @Override
    public void onDeviceText(String deviceId, String text) {
    }

    @Override
    public void onDeviceAbnormality(String deviceId, String abnormality) {
    }

    @Override
    public void onDeviceRecovered(String deviceId, String data) {
    }
}